package com.qlk.vorder.utils.http;

import com.qlk.common.utils.wrap.WrapMapper;
import com.qlk.common.utils.wrap.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * HTTP通信工具类
 * @author mangxiao
 * @since 2016-4-20
 */
public class HttpUtil {

	private static final Log log = LogFactory.getLog(HttpUtil.class);
	
	public static String post(String url, String mediaType, Map<String, String> map, int timeout) throws Exception{
		String r = null;
		CloseableHttpClient client = HttpClients.createDefault();
		RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).build();
		
		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
		for (String key : map.keySet()) {
			parameters.add(new BasicNameValuePair(key,map.get(key)));
		}
		
		HttpPost post = new HttpPost(url);
		post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
		post.setConfig(config);
		
		CloseableHttpResponse response = client.execute(post);
		try {
			int statusCode = response.getStatusLine().getStatusCode();
			log.info("statusCode::" + statusCode);
			HttpEntity e = response.getEntity();
			r = EntityUtils.toString(e,"UTF-8");
			log.info("r:#" + r);
		} finally {
		    response.close();
		}
		return r;
	}
	

	/**
	 * 重写一个Wrapper<String>返回值的Post方法
	 * @param url
	 * @param map
	 * @param timeout
	 * @return
	 * @throws Exception
	 */
	public static Wrapper<String> post(String url, Map<String, String> map, int timeout) throws Exception{
		Map<Integer,String> ret = new HashMap<Integer,String>();
		String r = null;
		CloseableHttpClient client = HttpClients.createDefault();
		RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).build();
		
		List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
		for (String key : map.keySet()) {
			parameters.add(new BasicNameValuePair(key,map.get(key)));
		}
		
		HttpPost post = new HttpPost(url);
		post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
		post.setConfig(config);
		
		CloseableHttpResponse response = client.execute(post);
		try {
			int statusCode = response.getStatusLine().getStatusCode();
			log.info("statusCode::" + statusCode);
			if(200 == statusCode){
				HttpEntity e = response.getEntity();
				r = EntityUtils.toString(e,"UTF-8");
				log.info("r:#" + r);
				ret.put(statusCode, r);
				return WrapMapper.wrap(statusCode, "操作成功", r);
			}else{
				ret.put(statusCode, "通信异常");
				return WrapMapper.wrap(statusCode, "通信异常", EntityUtils.toString(response.getEntity(), "UTF-8"));
			}
		} finally {
		    response.close();
		}
	}

    /**
     * get
     * @param url
     * @param timeout
     * @return
     * @throws Exception
     */
    public static String get(String url,Map<String,Object> map, int timeout) throws Exception{
        if(StringUtils.isBlank(url))
            return null;
        Map<Integer,String> ret = new HashMap<Integer,String>();
        String r = null;
        CloseableHttpClient client = HttpClients.createDefault();
        //RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).build();
      /*  if("?".equals(url.substring(url.length()-1))){

        }*/
        if(map != null){
            StringBuffer buffer = new StringBuffer();
            for(String key : map.keySet()){
                buffer.append("&"+key+"="+map.get(key));
            }
            if(buffer.length()>0){
                url = url+"?" +buffer.substring(1);
            }
        }
        HttpGet getMethod = new HttpGet();
        getMethod.addHeader("Content-type" , "text/html; charset=utf-8"); 
        getMethod.setURI(new URI(url));
        CloseableHttpResponse response = client.execute(getMethod);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            log.info("statusCode::" + statusCode);
            HttpEntity e = response.getEntity();
            r = EntityUtils.toString(e, "UTF-8");
            log.warn("r:#" + r);
        } finally {
            response.close();
        }
        return  r;
    }

    /**
     *
     * @param url 请求发的url地址
     * @param map 请求参数
     * @param connectTimeout 设置连接超时时间，单位毫秒。
     * @param connectionRequestTimeout 设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
     * @param socketTimeout 请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
     * @return
     * @throws Exception
     * @Description:
     */
    public static String getForObject(String url, Map<String, String> map,int connectTimeout,int connectionRequestTimeout ,int socketTimeout) throws Exception {
        if (map != null && !map.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            sb.append("?");
            int a = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (a != 0) {
                    sb.append("&");
                }
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
                a++;
            }
            url += sb.toString();
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-type" , "text/html; charset=utf-8"); 
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout*1000).setConnectionRequestTimeout(connectionRequestTimeout*1000)
                .setSocketTimeout(socketTimeout*1000).build();
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        int code = response.getStatusLine().getStatusCode();
        String retStr = "";
        // 判断请求是否成功
        if (code == 200) {
            // 获取返回的实体
            HttpEntity entity = response.getEntity();// 得到请求回
            // 获取返回的内容
            retStr = EntityUtils.toString(entity, "UTF-8");
        } else {
        	throw new Exception(String.valueOf(code));
        }
        return retStr;
    }

    public static void main(String[] args){
		String url = "http://api_ofc.oss.7lk.cn/order_apiv1/orders/list.json";
		
		Map<String, String> map = new HashMap<String, String>();
    	//map.put("order_ids", "D1602030000002");//正确
    	//map.put("source_orders", "15052717561296213629");//有问题
    	//map.put("order_status", "1");//有问题
    	//map.put("payment_type", "2");//正确
    	//map.put("consignee_mobile", "139898980");//正确
    	//map.put("consignee_name", "ALEX");//正确
    	
    	//map.put("order_date_start", "1900-01-01 00:00:00");
    	//map.put("order_date_end", "2016-02-025 00:00:00");
    	
    	
    	//map.put("order_date_start", "1900-01-01 00:00:00");
    	//map.put("order_date_end", "2100-01-01 00:00:00");
    	map.put("page", "1");
    	map.put("rows", "100");
    	//String data = null;
    	
    	String body;
		try {
			body = HttpUtil.post(url, null, map,30);
			System.out.println(body);
			
			ObjectMapper mapper = new ObjectMapper();  
		    JsonNode root = mapper.readTree(body); 
//		    JsonNode data = root.path("data");
		    JsonNode codeJN = root.path("code");
		    int code = codeJN.asInt();
		    System.out.println(code);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
